package com.pureut.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.SupplierAccess;
import com.pureut.system.domain.SupplierEvaluation;
import com.pureut.system.domain.SupplierList;
import com.pureut.system.domain.dto.SupplierEvaluationPagesDto;
import com.pureut.system.domain.vo.SupplierAccessVo;
import com.pureut.system.domain.vo.SupplierEvaluationVo;
import com.pureut.system.export.SupplierEvaluationExport;
import com.pureut.system.export.SupplierExport;
import com.pureut.system.mapper.SupplierEvaluationMapper;
import com.pureut.system.mapper.SupplierListMapper;
import com.pureut.system.service.ISupplierEvaluationService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author: pureut
 * @Date: 2024-12-05 17:16:19
 * @Desc: 供应商评价
 */
@Service("supplierEvaluationService")
public class SupplierEvaluationServiceImpl extends ServiceImpl<SupplierEvaluationMapper, SupplierEvaluation> implements ISupplierEvaluationService {

    /**
     * 供应商评价Dao
     */
    @Resource
    private SupplierEvaluationMapper supplierEvaluationMapper;

    @Resource
    FeignService feignService;

    /**
     * 供应商名录Dao
     */
    @Resource
    private SupplierListMapper supplierListMapper;

    /**
     * 查询列表
     * @param supplierEvaluationVo
     * @return
     */
    @Override
    public List<SupplierEvaluationPagesDto> queryPage(SupplierEvaluationVo supplierEvaluationVo) {
        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierEvaluationPagesDto> supplierEvaluationPagesDtos = supplierEvaluationMapper.selectByPage(supplierEvaluationVo);
        supplierEvaluationPagesDtos.forEach(e->{
            e.setPreChangeGrade(netMap.get(String.valueOf(e.getPreChangeGrade())));
            e.setModifiedGrade(netMap.get(String.valueOf(e.getModifiedGrade())));

        });
        return supplierEvaluationPagesDtos;
    }


    /**
     * 新增供应商评价
     * @param supplierEvaluationVo
     * @return
     */
    @Override
    public Boolean save(SupplierEvaluationVo supplierEvaluationVo) {
        SupplierEvaluation supplierEvaluation = new SupplierEvaluation();
        BeanUtil.copyProperties(supplierEvaluationVo, supplierEvaluation);
        supplierEvaluation.setCreateBy(SecurityUtils.getUsername());
        supplierEvaluation.setCreateTime(new Date());
        String sn = feignService.getAuthorityCoding("warehouse:outbound:reworksto:list");
        if (sn == null) {
            throw new GlobalException("该单据未进行配置,无法生成单据编码");
        }
        supplierEvaluation.setEvaluationCode(sn);
        SupplierList supplierList = supplierListMapper.selectById(supplierEvaluationVo.getSupplierId());
        supplierEvaluation.setPreChangeGrade(supplierList.getSupplierLevel());
        supplierEvaluation.setStatus("1");

        return save(supplierEvaluation);
    }


    /**
     * 更新供应商评价
     * @param supplierEvaluationVo
     * @return
     */
    @Override
    public Boolean updateById(SupplierEvaluationVo supplierEvaluationVo) {
        SupplierEvaluation supplierEvaluation = new SupplierEvaluation();
        BeanUtil.copyProperties(supplierEvaluationVo, supplierEvaluation);
        supplierEvaluation.setUpdateBy(SecurityUtils.getUsername());
        supplierEvaluation.setUpdateTime(new Date());
        return updateById(supplierEvaluation);
    }

    /**
     * 提交
     * @param id
     * @return
     */
    @Override
    public Boolean submit(Long id){
        SupplierEvaluation supplierAccess = new SupplierEvaluation();
        supplierAccess.setId(id);
        supplierAccess.setStatus("2");
        return updateById(supplierAccess);
    }

    /**
     * 审核
     * @param supplierAccessVo
     * @return
     */
    @Transactional
    @Override
    public Boolean examine(SupplierAccessVo supplierAccessVo){
        SupplierEvaluation supplierAccess = getById(supplierAccessVo.getId());
        supplierAccess.setId(supplierAccessVo.getId());
        if(supplierAccessVo.getAuditState()==1){
            supplierAccess.setStatus("3");
        }else{
            supplierAccess.setStatus("4");
        }
        supplierAccess.setApproverBy(SecurityUtils.getUsername());
        supplierAccess.setApprovalTime(new Date());
        boolean b = updateById(supplierAccess);
        if(b&&("3").equals(supplierAccess.getStatus())){
            SupplierList supplierList=new SupplierList();
            supplierList.setId(supplierAccess.getSupplierId());
            supplierList.setSupplierLevel(supplierAccess.getModifiedGrade());
            supplierListMapper.updateById(supplierList);
        }
        return b;
    }

    /**
     * 供应商评价导出
     * @param supplierEvaluationVo
     * @return
     */
    @Override
    public List<SupplierEvaluationPagesDto> getInfoExport(SupplierEvaluationVo supplierEvaluationVo)
    {
        if (supplierEvaluationVo.getIdStr() != null) {

            List<String> idList = Arrays.asList(supplierEvaluationVo.getIdStr().split(","));

            supplierEvaluationVo.setIds(idList);
        }

        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierEvaluationPagesDto> supplierEvaluationPagesDtos = supplierEvaluationMapper.selectByPage(supplierEvaluationVo);
        supplierEvaluationPagesDtos.forEach(e->{
            e.setPreChangeGrade(netMap.get(String.valueOf(e.getPreChangeGrade())));
            e.setModifiedGrade(netMap.get(String.valueOf(e.getModifiedGrade())));

        });
        return supplierEvaluationPagesDtos;
    }

    /**
     * 供应商评价导入
     * @param coCustomer
     * @return
     */
    @Override
    public String importMouldData(List<SupplierEvaluationExport> coCustomer)
    {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入供应商评价不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<SysDictData> netArray = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap( SysDictData::getDictLabel,SysDictData::getDictValue));

        List<SupplierList> supplierLists = supplierListMapper.selectList(new QueryWrapper<>());
        Map<String, Long> supplierMap = supplierLists.stream().collect(Collectors.toMap(SupplierList::getSupplierName, SupplierList::getId));


        for (SupplierEvaluationExport supplierExport : coCustomer) {
            SupplierEvaluation supplierEvaluation = new SupplierEvaluation();
            try {

                supplierEvaluation.setSupplierId(supplierMap.get(supplierExport.getSupplierName()));
                //供应商等级
                supplierEvaluation.setPreChangeGrade(netMap.get(supplierExport.getPreChangeGrade()));
                //变更等级
                supplierEvaluation.setModifiedGrade(netMap.get(supplierExport.getModifiedGrade()));

                String sn = feignService.getAuthorityCoding("warehouse:outbound:reworksto:list");
                if (sn == null) {
                    throw new GlobalException("该单据未进行配置,无法生成单据编码");
                }
                supplierEvaluation.setEvaluationCode(sn);
                supplierEvaluation.setEvaluationContent(supplierEvaluation.getEvaluationContent());

                boolean save = save(supplierEvaluation);

                if (!save) {
                    throw new GlobalException("导入失败");
                }

                successNum++;
                successMsg.append(successNum).append("、供应商评价 ").append(supplierExport.getSupplierName()).append(" 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、供应商评价 " + supplierExport.getSupplierName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
